from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import User

# Create your views here.


# 检验登陆后的cookies是否在有效期内，不在有效期重新登陆
def login_check(func):
    def inner(request, *args, **kwargs):
        login_status = request.get_signed_cookie('login_status', default='', salt='tian')
        if login_status != '1':  # cookies失效返回登陆页面
            return redirect('myapp:login')
        ret = func(request, *args, **kwargs)
        return ret
    return inner


# 登陆的函数
def login(request):
    if request.method == 'GET':
        return render(request, 'myapp/login.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        result = User.objects.filter(uname=username, upassword=password).count()
        # 检验用户名密码
        if result:
            response = redirect('myapp:index')  # 跳转页面
            response.set_cookie('login_status', 1, max_age=60 * 60 * 24 * 7)  # 为跳转后的页面设置cookies状态和跳转时间
            response.set_signed_cookie('login_status', 1, salt='tian')  # 加密的cookies
            return response
        else:
            return HttpResponse('用户名密码错误')


@login_check
def index(request):
    ret = request.get_signed_cookie('login_status', default='', salt='tian')
    return render(request, 'myapp/index.html', context={'login_status': ret})


@login_check
def home(request):
    ret = request.get_signed_cookie('login_status', default='', salt='tian')
    return render(request, 'myapp/home.html', context={'login_status': ret})


def login_out(request):
    ret = redirect(to='myapp:login')
    ret.delete_cookie('login_status')
    return ret